package cn.itcast.nems.manager.util;

import com.fasterxml.jackson.core.JsonGenerator;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.PropertyNamingStrategies;
import org.springframework.util.Assert;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 功能描述:
 * JSONArray转实体entity工具类
 */
public class JSONArrayToEntityConverter {
    private static final ObjectMapper objectMapper = new ObjectMapper()
            .setPropertyNamingStrategy(PropertyNamingStrategies.SNAKE_CASE)
            .configure(JsonGenerator.Feature.IGNORE_UNKNOWN, true);

    public static <T> T convert(String formJsons, Class<T> beanClass) {
        List<AdditionalFormField> fields = null;
        try {
            fields = objectMapper.readValue(
                    formJsons,
                    new TypeReference<List<AdditionalFormField>>() {
                    }
            );
        } catch (JsonProcessingException e) {
            throw new RuntimeException(e);
        }
        Map<String, Object> fieldValues = new HashMap<>();
        for (AdditionalFormField field : fields) {
            Assert.hasText(field.getFieldKey(), "key不能为空");
            Assert.isTrue(!fieldValues.containsKey(field.getFieldKey()), "key重复");
            fieldValues.put(field.getFieldKey(), field.getFieldValue());
        }
        return objectMapper.convertValue(fieldValues, beanClass);
    }
}
